import { useEffect, useState } from 'react';
import style from './index.module.scss';
import tmBg from '@/assets/images/qixi/甜蜜来袭@2x.png';
import gbBg from '@/assets/images/qixi/爱情告白@2x.png';
import tmTitle from '@/assets/images/qixi/恋爱来袭榜@2x.png';
import gbTitle from '@/assets/images/qixi/恋爱告白榜@2x.png';
import flowerL from '@/assets/images/qixi/花瓣2.png';
import flowerR from '@/assets/images/qixi/花瓣1.png';
import bird from '@/assets/images/qixi/飞鸟@2x.png';

import Icon1 from '@/assets/images/qixi/1.png';
import Icon2 from '@/assets/images/qixi/2.png';
import Icon3 from '@/assets/images/qixi/3.png';

import { goConfession, goHisConfession, goUserPage, showToast } from './util';

const domain = `https://webapi.pupupal.com`;
const Content = ({ type }) => {
    const urlParams = new URLSearchParams(window.location.search);
    const authorizationToken = urlParams.get('userId');
    console.log('authorizationToken', authorizationToken);

    // 1甜蜜来袭 2爱情告白
    const [data, setData] = useState([]);
    const [info, setInfo] = useState(); // 当前用户信息
    const [showMsg, setShowMsg] = useState(false);

    const getSweetRank = async () => {
        fetch(`${domain}/gift/rank/sweet/rank`, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    setData(response.data.list || []);
                    setInfo(response.data.myRank);
                } else {
                    console.error('Failed to fetch ranking data:');
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const getLikeRank = async () => {
        fetch(`${domain}/forum/forum/likeNum/rank`, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    setData(response.data.list || []);
                    setInfo(response.data.myRank);
                } else {
                    console.error(
                        'Failed to fetch ranking data:',
                        response.msg
                    );
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const fetchSubscribe = async (item, url) => {
        fetch(url, {
            method: 'POST',
            headers: {
                Authorization: authorizationToken,
                'content-type': 'application/json',
            },
            body: JSON.stringify({
                targetUserId: item.userId,
                userId: info.userId,
            }),
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    console.log('成功');
                    if (type === 1) {
                        getSweetRank();
                    } else {
                        getLikeRank();
                    }
                } else {
                    console.error(
                        'Failed to fetch ranking data:',
                        response.msg
                    );
                    showToast(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const clickSubscribe = async (item) => {
        if (item.relation === 2 || item.relation === 3) {
            fetchSubscribe(item, `${domain}/user/friend/subscribe`); // 去关注
        } else if (item.relation === 1 || item.relation === 4) {
            fetchSubscribe(item, `${domain}/user/friend/unsubscribe`); // 取消关注
        }
    };

    const clickToConfession = () => {
        const u = navigator.userAgent;
        const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        console.log('是否是Android：' + isAndroid);
        console.log('是否是iOS：' + isiOS);
        if (isiOS) {
            setShowMsg(true);
        } else {
            goConfession();
        }
    };

    useEffect(() => {
        if (authorizationToken) {
            if (type === 1) {
                getSweetRank();
            } else {
                getLikeRank();
            }
        } else {
            console.error('Authorization token not found in URL');
        }
    }, []);
    return (
        <>
            <div className={style.content_wrap}>
                <div className={style.gift}>
                    <img src={type === 1 ? tmBg : gbBg} alt="" />
                    <img className={style.flower_left} src={flowerL} alt="" />
                    <img className={style.flower_right} src={flowerR} alt="" />
                    {type === 1 && (
                        <img className={style.bird} src={bird} alt="" />
                    )}
                    <div
                        className={style.gaobai}
                        onClick={() => clickToConfession()}
                    ></div>
                </div>
                <div className={style.rank_container}>
                    <div className={style.title_box}>
                        <img src={type === 1 ? tmTitle : gbTitle} alt="" />
                    </div>
                    <div className={style.rank_box}>
                        <div className={style.rank_list}>
                            {data.map((item, i) => (
                                <div
                                    className={style.td_box}
                                    key={item?.userId}
                                >
                                    {i === 0 && (
                                        <div className={style.rank}>
                                            <img src={Icon1}></img>
                                        </div>
                                    )}
                                    {i === 1 && (
                                        <div className={style.rank}>
                                            <img src={Icon2}></img>
                                        </div>
                                    )}
                                    {i === 2 && (
                                        <div className={style.rank}>
                                            <img src={Icon3}></img>
                                        </div>
                                    )}
                                    {i > 2 && (
                                        <div className={style.rank}>
                                            {i >= 99 ? '99+' : i + 1}
                                        </div>
                                    )}
                                    <div className={style.user}>
                                        <img
                                            src={item?.avatar}
                                            alt=""
                                            onClick={() =>
                                                goUserPage(item.userId)
                                            }
                                        />
                                        <div>
                                            <div className={style.nickname}>
                                                {item.nickname || item.account}
                                            </div>
                                            <div className={style.score}>
                                                {type === 1
                                                    ? '甜蜜值'
                                                    : '点赞数'}
                                                {item?.showValue}
                                            </div>
                                        </div>
                                    </div>
                                    {type === 1 && (
                                        <div
                                            className={
                                                item.relation === 1 ||
                                                item.relation === 4
                                                    ? style.rankBtn_blue
                                                    : style.rankBtn
                                            }
                                            onClick={() => clickSubscribe(item)}
                                            style={{
                                                opacity:
                                                    item.relation < 5 ? 1 : 0.6,
                                            }}
                                        >
                                            {item.relation === 1 && '已关注'}
                                            {item.relation === 2 && '回关+'}
                                            {item.relation === 3 && '关注+'}
                                            {item.relation === 4 && '已互关'}
                                            {item.relation === 5 && '关注+'}
                                        </div>
                                    )}
                                    {type === 2 && (
                                        <div
                                            className={style.rankBtn}
                                            onClick={() =>
                                                goHisConfession(
                                                    item?.mostLikedForumId
                                                )
                                            }
                                        >
                                            TA的告白
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
            <div
                className={`${style.user_box} ${
                    type === 1 ? style.user_box_lianai : style.user_box_gaobai
                }`}
            >
                <div className={style.user_content}>
                    <div className={style.left}>
                        <div className={style.my_rank_index}>
                            {info?.rank === 0 ? '未上榜' : info?.rank}
                        </div>
                    </div>
                    <div className={style.user}>
                        <img src={info?.avatar} alt="" />
                        {info?.nickname || info?.account}
                    </div>
                    <div className={style.right}>
                        <div className={style.my_rank_desc}>
                            {type === 1 ? '七夕甜蜜值' : '点赞数'}
                        </div>
                        <div className={style.my_rank_num}>
                            {info?.showValue || 0}
                        </div>
                    </div>
                </div>
            </div>
            {showMsg && (
                <div className={style.messageBox}>
                    <div className={style.message}>
                        <p>
                            在广场-【发动态】【选择话题】-选择
                            <span>#七夕爱情告白#</span>
                            话题参与活动
                        </p>
                        <div onClick={() => setShowMsg(false)}>关闭</div>
                    </div>
                </div>
            )}
        </>
    );
};

export default Content;
